<template>
  <div class="custom-reports">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">自定义报表</h1>
        <p class="page-description">创建和管理个性化的业务报表</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建报表
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-item">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索报表名称..."
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="filter-item">
            <el-select v-model="statusFilter" placeholder="状态筛选" @change="handleStatusFilter">
              <el-option label="全部" value="all" />
              <el-option label="草稿" value="draft" />
              <el-option label="已发布" value="published" />
              <el-option label="已归档" value="archived" />
            </el-select>
          </div>
          <div class="filter-item">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleSort">
              <el-option label="创建时间" value="createTime" />
              <el-option label="更新时间" value="updateTime" />
              <el-option label="名称" value="name" />
            </el-select>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 报表列表 -->
    <div class="reports-list">
      <el-card>
        <el-table 
          :data="filteredReports" 
          v-loading="loading"
          stripe
          @row-click="handleRowClick"
        >
          <el-table-column prop="name" label="报表名称" min-width="200">
            <template #default="{ row }">
              <div class="report-name-cell">
                <el-icon :color="getStatusColor(row.status)">
                  <Document />
                </el-icon>
                <span>{{ row.name }}</span>
                <el-tag 
                  :type="getStatusType(row.status)" 
                  size="small"
                  class="status-tag"
                >
                  {{ getStatusText(row.status) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
          
          <el-table-column prop="creator" label="创建者" width="120" />
          
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="updateTime" label="更新时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.updateTime) }}
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button size="small" type="primary" @click.stop="editReport(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button size="small" @click.stop="previewReport(row)">
                  <el-icon><View /></el-icon>
                  预览
                </el-button>
                <el-dropdown @command="handleCommand" trigger="click">
                  <el-button size="small" type="info">
                    更多
                    <el-icon><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="`copy-${row.id}`">
                        <el-icon><CopyDocument /></el-icon>
                        复制
                      </el-dropdown-item>
                      <el-dropdown-item :command="`export-${row.id}`">
                        <el-icon><Download /></el-icon>
                        导出
                      </el-dropdown-item>
                      <el-dropdown-item :command="`delete-${row.id}`" divided>
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalReports"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑报表对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      :title="isEditing ? '编辑报表' : '新建报表'"
      width="60%"
      top="5vh"
      class="create-report-dialog"
    >
      <ReportBuilder
        v-if="createDialogVisible"
        :report="currentEditReport"
        :is-editing="isEditing"
        @save="handleSaveReport"
        @cancel="handleCancelEdit"
      />
    </el-dialog>

    <!-- 报表预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="currentPreviewReport?.name"
      width="80%"
      top="5vh"
      class="report-preview-dialog"
    >
      <ReportPreview
        v-if="previewDialogVisible && currentPreviewReport"
        :report="currentPreviewReport"
        @export="handleExport"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Document, Edit, View, ArrowDown,
  CopyDocument, Download, Delete
} from '@element-plus/icons-vue'
import ReportBuilder from './components/ReportBuilder.vue'
import ReportPreview from './components/ReportPreview.vue'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('all')
const sortBy = ref('updateTime')
const currentPage = ref(1)
const pageSize = ref(20)

const createDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const isEditing = ref(false)
const currentEditReport = ref(null)
const currentPreviewReport = ref(null)

// 自定义报表列表
const customReports = ref([
  {
    id: 1,
    name: '月度用户增长报表',
    description: '分析每月新增用户数量和增长趋势',
    status: 'published',
    creator: '张三',
    createTime: '2024-01-10 10:30:00',
    updateTime: '2024-01-15 14:20:00',
    config: {}
  },
  {
    id: 2,
    name: '商品销售排行榜',
    description: '统计各商品的销售数量和金额排名',
    status: 'draft',
    creator: '李四',
    createTime: '2024-01-12 09:15:00',
    updateTime: '2024-01-14 16:45:00',
    config: {}
  },
  {
    id: 3,
    name: '客户流失分析报表',
    description: '分析客户流失原因和流失率趋势',
    status: 'published',
    creator: '王五',
    createTime: '2024-01-08 11:20:00',
    updateTime: '2024-01-13 13:30:00',
    config: {}
  }
])

// 计算属性
const filteredAndSortedReports = computed(() => {
  let reports = customReports.value

  // 搜索过滤
  if (searchKeyword.value) {
    reports = reports.filter(report =>
      report.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      report.description.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }

  // 状态过滤
  if (statusFilter.value !== 'all') {
    reports = reports.filter(report => report.status === statusFilter.value)
  }

  // 排序
  reports.sort((a, b) => {
    if (sortBy.value === 'name') {
      return a.name.localeCompare(b.name)
    } else if (sortBy.value === 'createTime') {
      return new Date(b.createTime) - new Date(a.createTime)
    } else {
      return new Date(b.updateTime) - new Date(a.updateTime)
    }
  })

  return reports
})

const totalReports = computed(() => {
  return filteredAndSortedReports.value.length
})

const filteredReports = computed(() => {
  const reports = filteredAndSortedReports.value

  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return reports.slice(start, end)
})

// 方法
const handleSearch = () => {
  currentPage.value = 1
}

const handleStatusFilter = () => {
  currentPage.value = 1
}

const handleSort = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const showCreateDialog = () => {
  isEditing.value = false
  currentEditReport.value = null
  createDialogVisible.value = true
}

const editReport = (report) => {
  isEditing.value = true
  currentEditReport.value = { ...report }
  createDialogVisible.value = true
}

const handleSaveReport = (reportData) => {
  if (isEditing.value) {
    // 更新报表
    const index = customReports.value.findIndex(r => r.id === reportData.id)
    if (index !== -1) {
      customReports.value[index] = {
        ...reportData,
        updateTime: new Date().toLocaleString()
      }
    }
    ElMessage.success('报表更新成功')
  } else {
    // 新建报表
    const newReport = {
      ...reportData,
      id: Date.now(),
      creator: '当前用户',
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString()
    }
    customReports.value.unshift(newReport)
    ElMessage.success('报表创建成功')
  }
  createDialogVisible.value = false
}

const handleCancelEdit = () => {
  createDialogVisible.value = false
}

const previewReport = (report) => {
  currentPreviewReport.value = report
  previewDialogVisible.value = true
}

const handleRowClick = (row) => {
  previewReport(row)
}

const handleCommand = async (command) => {
  const [action, id] = command.split('-')
  const report = customReports.value.find(r => r.id === parseInt(id))
  
  switch (action) {
    case 'copy':
      // 复制报表
      const copiedReport = {
        ...report,
        id: Date.now(),
        name: `${report.name} - 副本`,
        status: 'draft',
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString()
      }
      customReports.value.unshift(copiedReport)
      ElMessage.success('报表复制成功')
      break
      
    case 'export':
      // 导出报表
      ElMessage.success('正在导出报表...')
      break
      
    case 'delete':
      // 删除报表
      try {
        await ElMessageBox.confirm('确定要删除这个报表吗？', '确认删除', {
          type: 'warning'
        })
        const index = customReports.value.findIndex(r => r.id === parseInt(id))
        if (index !== -1) {
          customReports.value.splice(index, 1)
        }
        ElMessage.success('报表删除成功')
      } catch {
        // 用户取消删除
      }
      break
  }
}

const handleExport = (format) => {
  ElMessage.success(`正在导出为 ${format} 格式...`)
}

const getStatusColor = (status) => {
  const colors = {
    draft: '#909399',
    published: '#67C23A',
    archived: '#E6A23C'
  }
  return colors[status] || '#909399'
}

const getStatusType = (status) => {
  const types = {
    draft: 'info',
    published: 'success',
    archived: 'warning'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    draft: '草稿',
    published: '已发布',
    archived: '已归档'
  }
  return texts[status] || '未知'
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

// 生命周期
onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.custom-reports {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header-content p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-card {
  border-radius: 8px;
}

.filter-content {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  min-width: 200px;
}

.reports-list {
  background: white;
  border-radius: 8px;
}

.report-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-tag {
  margin-left: auto;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.create-report-dialog :deep(.el-dialog__body),
.report-preview-dialog :deep(.el-dialog__body) {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}
</style>
